import { setCookie, getCookie } from '@/utils/common'

export default {
    namespaced: true,
    state: {
        theme: getCookie('theme') || 'dark',
        page_list: [{
            path: '/home',
            title: '首页'
        }]
    },
    mutations: {
        CHANGE_THEME(state) {
            let theme = state.theme == 'dark' ? 'light' : 'dark';
            state.theme = theme;
            setCookie('theme', theme);
        },
        ADD_PAGE_LIST(state, to) {
            let flag = true;
            state.page_list.map((item, index) => {
                item.path == to.path && (flag = false);
                index + 1 >= state.page_list.length && flag && state.page_list.push({
                    path: to.path,
                    title: to.meta.title
                })
            })
        },
        REMOVE_PAGE_LIST(state, { that, path }) {
            state.page_list.map((item, index) => {
                if (item.path == path) {
                    that.$route.path == path && that.$router.push(state.page_list[index - 1].path)
                    state.page_list.splice(index, 1);
                }
            });
        },
        CLEAR_ALL_TAGS(state) {
            state.page_list.splice(1);
        },
        CLEAR_OTHER_TAGS(state, vm) {
            let current = vm.$route;
            state.page_list = [{
                path: '/home',
                title: '首页'
            }, {
                path: current.path,
                title: current.meta.title
            }]
        }
    },
    actions: {
        addPageList({ commit }, to) {
            commit('ADD_PAGE_LIST', to)
        },
        removePageList({ commit }, { that, path }) {
            commit('REMOVE_PAGE_LIST', { that, path })
        },
        clearAllTags({ commit }) {
            commit('CLEAR_ALL_TAGS')
        },
        clearOtherTags({ commit }, vm) {
            commit('CLEAR_OTHER_TAGS', vm)
        }
    }
}